package org.lql.algo.codecrush.hot100.array;

import java.util.Arrays;

/**
 * @author: liangqinglong
 * @date: 2025-08-30 22:02
 * @description: 238. 除自身以外数组的乘积 <a href="https://leetcode.cn/problems/product-of-array-except-self/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class ProductExceptSelf {

	public int[] productExceptSelf(int[] nums) {
		int n = nums.length;
		int[] ans = new int[n];
		ans[0] = 1;
		// 计算每个元素左边元素的乘积
		for (int i = 1; i < n; i++) {
			ans[i] = nums[i - 1] * ans[i - 1];
		}
		// 计算每个元素右边元素的乘积
		int right = 1;
		for (int i = n - 1; i >= 0; i--) {
			ans[i] = ans[i] * right;
			right *= nums[i];
		}
		return ans;
	}

	public static void main(String[] args) {
		System.out.println(Arrays.toString(new ProductExceptSelf().productExceptSelf(new int[]{1, 2, 3, 4})));
		System.out.println(Arrays.toString(new ProductExceptSelf().productExceptSelf(new int[]{-1, 1, 0, -3, 3})));
	}
}
